
//const commonCfg = require('./webpack.common');
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
//const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
//webpack5已经不推荐使用,改用css-minimizer-webpack-plugin
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');

module.exports = function (env, argv, useBundleAnalyzerPlugin) {

    const isDevMode = (argv?.mode === 'development');
    const plugins = [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            filename: `index.html`,
            template: path.resolve(__dirname, `public/index.html`),
            inject: 'body',
            minify: isDevMode ? undefined : {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
        }),
    ];
    if (!isDevMode) {
        plugins.push(new MiniCssExtractPlugin({
            filename: '[name].[contenthash:8].css',
            chunkFilename: '[name].[contenthash:8].chunk.css',
        }));
    }
    if (useBundleAnalyzerPlugin) {
        plugins.push(new BundleAnalyzerPlugin());
    }

    return {
        mode: isDevMode ? 'development' : 'production',
        devtool: isDevMode ? 'cheap-module-source-map' : 'source-map',
        entry: {
            index: './src/pages/index.js',
        },
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: '[name].[contenthash:8].js',
            chunkFilename: '[name].[contenthash:8].chunk.js',
            publicPath: isDevMode ? undefined : './',
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    /*其他目录的css文件开启css模块化*/
                    exclude: [path.resolve(__dirname, 'src/styles'), /node_modules/],
                    use: [isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: { modules: true }
                    },
                        'postcss-loader']
                },
                {
                    test: /\.css$/,
                    /*默认的版本,即支持全局样式的配置*/
                    include: [path.resolve(__dirname, 'src/styles'), /node_modules/],
                    use: [isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
                },
                {
                    test: /\.less$/,
                    /*其他目录的less文件开启css模块化*/
                    exclude: [path.resolve(__dirname, 'src/styles'), /node_modules/],
                    use: [isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: { modules: true }
                    },
                        'postcss-loader', 'less-loader']
                },
                {
                    test: /\.less$/,
                    /*默认的版本,即支持全局样式的配置*/
                    include: [path.resolve(__dirname, 'src/styles'), /node_modules/],
                    use: [isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader']
                },
                {
                    test: /\.(png|svg|jpg|gif)$/,
                    use: [
                        {
                            loader: 'url-loader',
                            options: {
                                name: 'images/[name].[ext]',
                                esModule: false,
                                limit: 1024,  // 1kb
                            }
                        },
                    ],
                    //webpack5时,有点冲突,需要修改成这个类型,才可以按预期的解析
                    type: 'javascript/auto'
                },
                {
                    test: /\.(woff|ttf|eot|woff2)$/,
                    use: [
                        {
                            loader: 'file-loader',
                            options: {
                                name: 'fonts/[name].[ext]',
                                esModule: false,
                            }
                        },
                    ],
                    //webpack5时,有点冲突,需要修改成这个类型,才可以按预期的解析
                    type: 'javascript/auto'
                },
                {
                    test: /.\html$/,
                    //处理html中的依赖资源
                    loader: 'html-loader',
                    options: {
                        sources: {
                            list: [
                                //默认解析图片的src
                                {
                                    tag: "img",
                                    attribute: "src",
                                    type: "src",
                                },
                                //因为用了懒加载,data-src也要解析,不然图片会认为没用到
                                {
                                    tag: "img",
                                    attribute: "data-src",
                                    type: "src",
                                },
                                //响应式图片列表也要加入解析
                                {
                                    tag: "img",
                                    attribute: "data-srcset",
                                    type: "srcset",
                                },
                                {
                                    tag: "section",
                                    attribute: "data-bgset",
                                    type: "srcset",
                                },
                            ],
                        }
                    }
                },
                {
                    test: /\.m?js$/,
                    exclude: /(node_modules|bower_components)/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            //修改完记得同步到.babelrc, 方便eslint的babel解析使用
                            "presets": [
                                "@babel/preset-env",
                                "@babel/preset-react"
                            ],
                            "plugins": [
                                "@babel/plugin-transform-runtime",
                                "@babel/plugin-proposal-class-properties",
                                "react-hot-loader/babel",
                            ]
                        }
                    }
                },
            ]
        },
        plugins: plugins,
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'src'),
            }
        },
        optimization: isDevMode ? undefined : {
            minimize: true,
            minimizer: [
                new TerserWebpackPlugin(),
                new CssMinimizerWebpackPlugin(),
            ],
            splitChunks: {
                chunks: 'all',
                cacheGroups: {
                    defaultVendors: {
                        test: /[\\/]node_modules[\\/]/,
                        priority: -10,
                        reuseExistingChunk: true,
                        name: 'vendor'
                    },
                    default: {
                        minChunks: 2,
                        priority: -20,
                        reuseExistingChunk: true,
                        name: 'bundle'
                    }
                }
            }
        },
    };
};